using System;
using System.IO;
using System.Text;
using UnityEditor;

using UnityEngine;

namespace CGF
{
    public class CreateUIComponent
    {
        [MenuItem("Assets/创建 UIComponent")]
        public static void Create()
        {
            GameObject[] gos = Selection.GetFiltered<GameObject>(SelectionMode.Assets);
            for (int i = 0; i < gos.Length; i++)
            {
                CreateComponentWithPrefab(gos[i]);
            }
        }

        public static void CreateComponentWithPrefab(GameObject go)
        {
            string comTemPath = $"{Application.dataPath}/{Define.ScriptsHotfixFolder}/CGFramework/Editor/CreateUIComponent/Templates/UIComponent.cs.txt";

            string prefabFullPath = AssetDatabase.GetAssetPath(go);
            if (string.IsNullOrEmpty(prefabFullPath))
            {
                GameObject prefab = PrefabUtility.GetCorrespondingObjectFromOriginalSource(go);
                prefabFullPath = AssetDatabase.GetAssetPath(prefab);
            }
            if (string.IsNullOrEmpty(prefabFullPath))
            {
                UnityEditor.SceneManagement.PrefabStage prefabStage = UnityEditor.SceneManagement.PrefabStageUtility.GetPrefabStage(go);
                if (prefabStage)
                {
                    prefabFullPath = prefabStage.assetPath;
                }
            }
            prefabFullPath = Path.GetDirectoryName(prefabFullPath).Replace("\\", "/");
            string saveFolder = prefabFullPath.Substring(prefabFullPath.IndexOf("Prefabs"));
            string comCode = File.ReadAllText(comTemPath);
            comCode = comCode.Replace("#ClassName#", go.name);
            comCode = comCode.Replace("#PrefabPath#", $"{saveFolder}/{go.name}");
            if (go.GetComponent<Reference>())
            {
                comCode = comCode.Replace("#BindProperties#", "\n\t\t\tBindProperties(transform);");
            }
            else
            {
                comCode = comCode.Replace("#BindProperties#", "");
            }

            saveFolder = saveFolder.Substring("Prefabs".Length);
            saveFolder = $"{Application.dataPath}/{Define.DevelopScriptDir}{saveFolder}";
            string comSavePath = $"{saveFolder}/{go.name}.cs";
            if (!File.Exists(comSavePath)) SaveFile(comSavePath, comCode);

            Debug.Log($"生成 {go.name}.cs 脚本完成");

            //创建Partial类
            ReferenceEditor.CreateComponentPartial(go);

            AssetDatabase.Refresh();
        }

        private static void SaveFile(string path, string content)
        {
            string folder = Path.GetDirectoryName(path);
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            File.WriteAllText(path, content, new UTF8Encoding(false));
        }

    }
}